package com.shanghaionstar.carmanage.presenter;

import android.content.Context;
import android.support.annotation.NonNull;

import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.log.LogManager;

import com.onstar.cn.framework.mvp.base.IMVPScheduler;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.framework.utils.GsonHelper;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.sqlite.entities.OvdHistory;
import com.onstar.cn.mag.enumtype.RemoteCommandsType;
import com.onstar.cn.rxconstants.RxConstants;
import com.onstar.cn.vehicle.entity.RequestStatus;
import com.onstar.cn.vehicle.result.PollingResult;
import com.shanghaionstar.R;
import com.shanghaionstar.carmanage.iview.ICarStatusView;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.home.model.DiagnosticResponses;
import com.shanghaionstar.sqlite.DataRefreshDBService;
import com.shanghaionstar.service.DataRefreshService;
import com.shanghaionstar.report.bean.ReportReqParam;
import com.shanghaionstar.utils.ApplicationUtil;
import com.shanghaionstar.utils.BusinessUtil;

import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;

/**
 * Created by Yonglang Hong on 2016/8/2.
 */
public class CarStatusPresenter extends BasePresenter {

    private ICarStatusView statusView;
    //获取历史车况数据
    private DataRefreshDBService dataRefreshDBService;
    //刷新服务端车况数据
    private DataRefreshService dataRefreshService;

    private Subscription refreshSubscription, resultSubscription;

    private Context context;

    public CarStatusPresenter(IMVPScheduler mvpScheduler, Context context) {
        super(mvpScheduler);
        dataRefreshDBService = new DataRefreshDBService(context);
        dataRefreshService = new DataRefreshService(context);
        this.context = context;
    }

    public void setStatusView(@NonNull ICarStatusView statusView) {
        this.statusView = statusView;
    }

    public void getCarStatusFromDb(final String vin) {
        subscription = Observable.create(new Observable.OnSubscribe<DiagnosticResponses>() {
            @Override
            public void call(Subscriber<? super DiagnosticResponses> subscriber) {
                try {
                    OvdHistory statusData = dataRefreshDBService.getOvdHistory(vin);
                    if (statusData == null)
                        subscriber.onNext(null);
                    else {
                        DiagnosticResponses carStatus = GsonHelper.fromJson( statusData.getContent(),DiagnosticResponses.class);
                        subscriber.onNext(carStatus);
                    }
                } catch (Exception ex) {
                    subscriber.onError(ex);
                }
            }
        }).subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .subscribe(new Action1<DiagnosticResponses>() {
                    @Override
                    public void call(DiagnosticResponses carStatus) {
                        if (carStatus == null
                                || carStatus.getDiagnosticResponse() == null
                                || carStatus.getDiagnosticResponse().isEmpty()) {
                            statusView.showNoData();
                        } else {
                            statusView.showCarStatus(carStatus);
                        }
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        throwable.printStackTrace();
                        statusView.showOnErr(throwable);
                    }
                });
    }

    /**
     * datarefresh 入口方法
     *
     * @param
     */
    public void refreshVechileData() {
        refreshSubscription = dataRefreshService.doDataRefresh()
                .subscribeOn(mvpScheduler.backgroundThread())
                .observeOn(mvpScheduler.mainThread())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        statusView.showLoding();
                    }
                })
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        registPollingSub();
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {
                        //里面抛出的Error信息
                        statusView.showOnErr(throwable);
                    }
                });
    }

    /**
     * 处理Polling 返回结果
     */
    private void registPollingSub() {
        if (resultSubscription == null) {
            resultSubscription = RxBus.getDefault()
                    .toObserverable(RxConstants.ALL_PAGE_ALERT, PollingResult.class)
                    .subscribeOn(mvpScheduler.backgroundThread())
                    .observeOn(mvpScheduler.mainThread()).filter(new Func1<PollingResult, Boolean>() {
                        @Override
                        public Boolean call(PollingResult pollingResult) {
                            return RemoteCommandsType.COMMANDS_DIAGNOSTICS.value().equals(pollingResult.getRequestType());
                        }
                    })
                    .subscribe(new Action1<PollingResult>() {
                        @Override
                        public void call(PollingResult pollingResult) {
                            LogManager.getInstance().d("datarefresh result--->>" + pollingResult.getJson());
                            if (RequestStatus.Success.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.CarMngmt_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.CarMngmt_DragDownRefresh,true));
                                updateResultToDB(pollingResult.getJson(), pollingResult.getCompleteTime());
                                DiagnosticResponses status = GsonHelper.fromJson( pollingResult.getJson(),DiagnosticResponses.class);
                                statusView.showCompleteTime(pollingResult.getCompleteTime());
                                statusView.showCarStatus(status);
                            } else if (RequestStatus.Failure.getStringValue().equalsIgnoreCase(pollingResult.getRequestStatus())) {
                                /**
                                 * 刷新车况返回统一的错误?
                                 */
                                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.CarMngmt_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.CarMngmt_DragDownRefresh,false, pollingResult.getErrorInfo() == null ? "" : pollingResult.getErrorInfo().getMsg()));
                                statusView.showOnErr(new OnStarException("", context.getString(R.string.get_condition_error)));
                            } else {
                                //默认
                                BusinessUtil.sendReportByRequestParams(context, FunctionNameFindId.CarMngmt_DragDownRefresh.getStringValue(), ReportReqParam.getVehcileDataRefreshReqParam(FunctionNameFindId.CarMngmt_DragDownRefresh,false, pollingResult.getErrorInfo() == null ? "" : pollingResult.getErrorInfo().getMsg()));
                                statusView.showOnErr(new OnStarException("", context.getString(R.string.get_condition_error)));
                            }
                        }
                    }, new Action1<Throwable>() {
                        @Override
                        public void call(Throwable throwable) {
                            statusView.showOnErr(throwable);
                        }
                    });
        }
    }

    private void updateResultToDB(String json, String completionTime) {
        OvdHistory ovdhistory = new OvdHistory();
        ovdhistory.setVin(ApplicationUtil.getInstance().getVin());
        ovdhistory.setCreateDate(completionTime);
        ovdhistory.setContent(json);
        boolean isExits = dataRefreshDBService.checkDataIfExits(ApplicationUtil.getInstance().getVin());
        if (!isExits) {
            dataRefreshDBService.insert(ovdhistory); // 插入到本地数据
        } else {
            dataRefreshDBService.update(ovdhistory); // 更新本地数据
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (resultSubscription != null && !resultSubscription.isUnsubscribed()) {
            resultSubscription.unsubscribe();
            resultSubscription = null;
        }
        if (refreshSubscription != null && !refreshSubscription.isUnsubscribed()) {
            refreshSubscription.unsubscribe();
            refreshSubscription = null;
        }
    }
}
